<?php
/**
 * Pipahr
 *
 * @author Randy Zhao
 * @copyright 2013 pipahr.com
 */
JLoader::register("PCompanyHelper", OC::$SERVERROOT."/apps/company/lib/helper.php");
JLoader::register("PInterviewModelInterview", OC::$SERVERROOT."/apps/interview/lib/interview.php");
JLoader::register("PJobSeekerModelJobSeeker", OC::$SERVERROOT."/apps/jobseeker/lib/jobseeker.php");
JLoader::register('PCalendarHelper', OC::$SERVERROOT."/apps/calendar/lib/helper.php");


class PInterviewController
{
   // home page view
   public static function home() {
      disableIECache();
      $token = JRequest::getString("token", "");

      $latestToken = PInterviewHelper::getLatestToken($token);
      // This flag means: if token from get is not equal to token in DB, set change_token_flag to TRUE, then do redirect with new token
      $change_token_flag = false;
      if ($latestToken != $token) {
         $change_token_flag = true;
         $token = $latestToken;
      }

      if (empty($token)) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         return false;
      }

      if(PUtil::needSSL()) {
         OC_Response::redirect(PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("interview_home", array('token'=>$token))));
         exit;
      } elseif ($change_token_flag) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_home", array('token'=>$token)));
         exit;
      }

      $app = PFactory::getApplication();
      $isInviteToken = PInterviewHelper::isInviteToken($token);
      $app->setUserState("is_invite_token",$isInviteToken);

      $user = PFactory::getUser();
      if(isset($user->cb_usertype) && $user->cb_usertype == 'jobseeker'){
         $model = new PJobSeekerModelJobSeeker();
         $email = $model->join($token);
         if ( $email['email'] == $user->email ) {
            $app->setUserState("interview_token",$token);
            $app->setUserState("has_verified_token_".$token, true);
            OC_Response::redirect(OC_Helper::linkToRoute("interview_interview", array('token'=>$token)));
            exit;
         }
      }

      $model = new PInterviewModelInterview();
      $basicInfo = $model->getInfo($token);
      if (empty($basicInfo) || empty($token)) {
         if(OC_User::isLoggedIn())
            OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         else
            OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         exit;
      }

      $isRegistered = JobHelper::getUserByEmail($basicInfo->jobseeker_email);
      if (!empty($isRegistered)) {
         if(OC_User::isLoggedIn() && PFactory::isJobseekerUser()) {
            OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         } elseif (OC_User::isLoggedIn() && !PFactory::isJobseekerUser()) {
            OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         } else {
            // redirect to result to show a better login page - no surprise 
            OC_Response::redirect(OC_Helper::linkToRoute("interview_result", array('token'=>$token)));
         }
         exit; 
      } elseif (OC_User::isLoggedIn() && !PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         exit;
      }elseif (!OC_User::isLoggedIn()){
         if(OC_User::userExists($basicInfo->jobseeker_email)){
            OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
            exit;
         }
      }
    
      $isPaperSet = $model->isPaperSet($token);

      $tmpl = new OCP\Template('interview', 'home','base');
      $tmpl->assign('no_reg', true);
      $tmpl->assign('token', $token);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('isPaperSet', $isPaperSet);
      $tmpl->assign('isInviteToken', $isInviteToken);
      $tmpl->assign('page_title', '核对身份');
      $tmpl->printPage();
   }

   // verify this token's Attribution
   public static function verifyToken() {
      OC_JSON::setContentTypeHeader();
      $post = JRequest::get("post");
      $model = new PInterviewModelInterview();

      if (!$model->verifyToken($post)) {
         jexit(jsonError($model->getError(), null, false));
      }
      
      $token = JRequest::getString('token', '');
      $redirect_url = OC_Helper::linkToRoute("interview_interview", array('token'=>$token));
      // set a session for later use
      $app = PFactory::getApplication();
      $app->setUserState("has_verified_token_".$token,true);
      $app->setUserState("interview_token",$token);
      //need check current jobseeker had registed before,if registed before,set redirect url redirect jobseeker home page
      $model = new PJobSeekerModelJobSeeker();
      $user = $model->join($token);
      if(!empty($user['email'])) {
         $redirect_url = OC_Helper::linkToRoute("interview_home", array('token'=>$token));
      }
      jexit(jsonSuccess('success', $redirect_url, null, false));
   }

   // interview page view
   public static function interview() {
      disableIECache();
      if (OC_User::isLoggedIn() && !PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         exit;
      }
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", "");
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      $isInviteToken = $app->getUserState("is_invite_token");
      if (!$has_verified_token) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_home", array('token'=>$token)));
         exit;
      }

      $model = new PInterviewModelInterview();
      $interviewStat = $model->checkInterviewStat($token);
      if ($interviewStat) { // Check if jobseeker have done interview questions before
         if ($isInviteToken) { // If auto_invite is on, continue to online test
            OC_Response::redirect(OC_Helper::linkToRoute("interview_testnotice", array('token'=>$token)));
         } else { // Otherwise, it's an auto_send interview, just redirect to result page
            OC_Response::redirect(OC_Helper::linkToRoute("interview_result", array('token'=>$token)));
         }
         exit;
      }
      $basicInfo = $model->getInfo($token);
      $jobseeker_info = $model->getJobseekerInfo($token);
      $interview_questions = $model->getInterviewQuestions($basicInfo->job_id);
      if(empty($basicInfo) || empty($jobseeker_info) || empty($interview_questions)) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         exit;
      }

      $isPaperSet = $model->isPaperSet($token);

      $tmpl = new OCP\Template('interview', 'interview','base');
      $tmpl->assign('no_reg', true);
      $tmpl->assign('token', $token);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('isPaperSet', $isPaperSet);
      $tmpl->assign('isInviteToken', $isInviteToken);
      $tmpl->assign('jseeker_info', $jobseeker_info);
      $tmpl->assign('interview', $interview_questions);
      $tmpl->assign('page_title', '完善信息');
      $tmpl->printPage();
   }
   
   public static function giveup() {
      disableIECache();
      $token = JRequest::getString("token", "");
      $email = JRequest::getString("email", "");
      $app = PFactory::getApplication();

      $model = new PInterviewModelInterview();
      $basicInfo = $model->getInfo($token, $email);
      
      if (empty($basicInfo) || empty($token)) {
         if(OC_User::isLoggedIn())
            OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         else
            OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         exit;
      }

      $tmpl = new OCP\Template('interview', 'giveup','base');
      $tmpl->assign('token', $token);
      $tmpl->assign('email', $email);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('page_title', '核对身份');
      $tmpl->printPage();
   }
   
   public static function giveupconfirm() {
      OC_JSON::setContentTypeHeader();
      
      $model = new PInterviewModelInterview();
      if (!$model->giveupConfirm()) {
         jexit(jsonError($model->getError(), null, false));
      }
      jexit(jsonSuccess('操作成功', null, null, false));
   }

   // action to post interview question
   public static function postinterview() {
      OC_JSON::setContentTypeHeader();
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", "");
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      $isInviteToken = $app->getUserState("is_invite_token");
      if (!$has_verified_token) {
         jexit(jsonError("非法的请求", null, false));
      }

      $post = JRequest::get("post");
      $model = new PInterviewModelInterview();

      if (!$model->postinterview($post)) {
         jexit(jsonError($model->getError(), null, false));
      }

      $redirect_url = OC_Helper::linkToRoute("interview_testnotice", array('token'=>$token));

      $isPaperSet = $model->isPaperSet($token);
      if (!$isPaperSet || !$isInviteToken) {
         $redirect_url = OC_Helper::linkToRoute("interview_result", array('token'=>$token));
      }

      jexit(jsonSuccess('success', $redirect_url, null, false));
   }

   // testnotice page show before begin the test
   public static function testnotice() {
      disableIECache();
      if (OC_User::isLoggedIn() && !PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         exit;
      }
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", "");
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      $isInviteToken = $app->getUserState("is_invite_token");
      if (!$has_verified_token) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_home", array('token'=>$token)));
         exit;
      }

      $model = new PInterviewModelInterview();
      $basicInfo = $model->getInfo($token);
      if(empty($basicInfo) || !$isInviteToken) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         exit;
      }
   
      $qualifications = $model->validateToken($token);
      $takenExamBefore = $model->hasTakeExamBefore($token);
      $isRegistered = JobHelper::getUserByEmail($basicInfo->jobseeker_email);

      if ($takenExamBefore && !empty($isRegistered)) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home", array('token'=>$token)));
         exit;
      } elseif ($takenExamBefore) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_result", array('token'=>$token)));
         exit;
      }

      $baseExamInfo = $model->getBaseExamInfo($basicInfo->job_id, $token);
      if (empty($baseExamInfo)) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_result", array('token'=>$token)));
         exit;
      }

      $isPaperSet = $model->isPaperSet($token);

      $tmpl = new OCP\Template('interview', 'testnotice','base');
      $tmpl->assign('no_reg', true);
      $tmpl->assign('has_verified_token', $has_verified_token);
      $tmpl->assign('get_token', $token);
      $tmpl->assign('qualifications', $qualifications);
      $tmpl->assign('takenExamBefore', $takenExamBefore);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('isPaperSet', $isPaperSet);
      $tmpl->assign('isInviteToken', $isInviteToken);
      $tmpl->assign('baseExamInfo', $baseExamInfo);
      $tmpl->assign('page_title', '考试须知');
      $tmpl->printPage();
   }

   // test page show
   public static function jobtest() {
      disableIECache();
      if (OC_User::isLoggedIn() && !PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         exit;
      }
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", "");
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      $isInviteToken = $app->getUserState("is_invite_token");
      if (!$has_verified_token) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_home", array('token'=>$token)));
         exit;
      }

      $model = new PInterviewModelInterview();
      $basicInfo = $model->getInfo($token);
      if(empty($basicInfo) || !$isInviteToken) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         exit;
      }

      $baseExamInfo = $model->getBaseExamInfo($basicInfo->job_id, $token);
      if (empty($baseExamInfo)) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_result", array('token'=>$token)));
         exit;
      }

      $qualifications = $model->validateToken($token);
      if (!$qualifications) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_testnotice", array('token'=>$token)));
         exit;
      }

      $takenExamBefore = $model->hasTakeExamBefore($token);
      $isRegistered = JobHelper::getUserByEmail($basicInfo->jobseeker_email);

      if ($takenExamBefore && !empty($isRegistered)) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home", array('token'=>$token)));
         exit;
      } elseif ($takenExamBefore) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_result", array('token'=>$token)));
         exit;
      }

      $accepted_stat = $model->updateAccepted($token);
      if (!$accepted_stat) {
         OC_Response::redirect(OC_Helper::linkToRoute("interview_testnotice", array('token'=>$token)));
         exit;
      }

      $examPaper = $model->getExamQuestions($basicInfo->job_id, $baseExamInfo->sheetid);

      $isPaperSet = $model->isPaperSet($token);

      // Set sheet hits
      PInterviewHelper::updateSheetHits($baseExamInfo->sheetid);

      $tmpl = new OCP\Template('interview', 'jobtest','base');
      $tmpl->assign('no_reg', true);
      $tmpl->assign('token', $token);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('isPaperSet', $isPaperSet);
      $tmpl->assign('isInviteToken', $isInviteToken);
      $tmpl->assign('baseExamInfo', $baseExamInfo);
      $tmpl->assign('examPaper', $examPaper);
      $tmpl->assign('page_title', '线上笔试');
      $tmpl->printPage();
   }

   // load more exam questions
   public static function loadmore() {
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", ""); 
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      if (!$has_verified_token) {
         return;
      }

      $get = JRequest::get("get");

      $start = $get['last_end'];
      $total = $get['total_num'];
      if ($start > $total) {
         return;
      }

      $model = new PInterviewModelInterview();
      $qualifications = $model->validateToken($token, true);
      if (!$qualifications) {
         echo $model->getError();
         return;
      }
      $basicInfo = $model->getInfo($token);
      if(empty($basicInfo)) {
         echo "非法的请求"; 
         return; 
      }

      $baseExamInfo = $model->getBaseExamInfo($basicInfo->job_id, $token);
      $sheetid = $app->getUserState("the_sheetid");
      $examPaper = $model->getExamQuestions($basicInfo->job_id, $baseExamInfo->sheetid, $start, 5);

      $tmpl = new OCP\Template('interview', 'loadmore','');
      $tmpl->assign('has_verified_token', $has_verified_token);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('baseExamInfo', $baseExamInfo);
      $tmpl->assign('examPaper', $examPaper);
      $tmpl->assign('start', $start);
      $tmpl->printPage();
   }

   // sync the timer to avoid bad guy's hack
   public static function synctimer() {
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", ""); 
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      if (!$has_verified_token) {
         return;
      }

      $get = JRequest::get("get","");
      $jstime = $get['jstime'];
      $job_id = $get['job_id'];

      $model = new PInterviewModelInterview();
      $baseExamInfo = $model->getBaseExamInfo($job_id, $token, true);
      $realtime = $model->syncTimer($jstime,$token,$baseExamInfo->totaltime);

      if (is_int($realtime))
         jexit(json_encode($realtime));
   }

   // action to post exam answers
   public static function postexam() {
      OC_JSON::setContentTypeHeader();
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", ""); 
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      if (!$has_verified_token) {
         jexit(jsonError("非法的请求", null, false));
      }

      $model = new PInterviewModelInterview();
      $qualifications = $model->validateToken($token,true);
      if (!$qualifications) {
         jexit(jsonError($model->getError(), null, false));
      }

      $post = JRequest::get('post', JREQUEST_ALLOWRAW);

      if (!$model->postExam($post)) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('success', OC_Helper::linkToRoute("interview_result", array('token'=>$token)), null, false));
   }

   // after finish the test, show this result page
   public static function result() {
      disableIECache();
      $app = PFactory::getApplication();
      $token = JRequest::getString("token", "");
      $has_verified_token = $app->getUserState("has_verified_token_".$token);
      $isInviteToken = $app->getUserState("is_invite_token");

      $model = new PInterviewModelInterview();
      $basicInfo = $model->getInfo($token);
      $isPaperSet = $model->isPaperSet($token);
      $isRegistered = false;
      if(empty($basicInfo)) {
         if(OC_User::isLoggedIn() && PFactory::isJobseekerUser()) {
            OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home", array('token'=>$token)));
         } elseif (OC_User::isLoggedIn() && !PFactory::isJobseekerUser()) {
            OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         } else {
            OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
         }
         exit;
      }
      else {
         $isRegistered = JobHelper::getUserByEmail($basicInfo->jobseeker_email); 
         if(empty($isRegistered) && !$has_verified_token) {
            OC_Response::redirect(OC_Helper::linkToRoute("interview_error"));
            exit;
         }
      }
      // Get job's requirements
      $job_req = $model->getJobReq($token);
      // Add interview to req
      if (empty($job_req))
         $job_req = new stdclass();

      $job_req->interview = 1;
      $page_title = $isRegistered ? "线上竞聘" : "提交成功";

      $interview_stats = PInterviewHelper::getInterviewProgress($basicInfo->jobseeker_id,$basicInfo->employer_id);
      $details_arr = array(
         'interview'=>'<span class="red">完善信息</span>',
         'onlinetest'=>'<span class="red">线上笔试</span>',
         'persontest'=>'<span class="red">性格测试</span>'
         );
      $todo_list = array();
      foreach ($details_arr as $k => $v) {
         if (isset($job_req->$k) && $job_req->$k != 0) {
            if (!isset($interview_stats[$k])) {
               $todo_list[] = $v;
            }
         }
      }

      if (!empty($todo_list)) {
         $todo_list_text = implode('和', $todo_list);
      } else {
         $todo_list_text = "";
      }

      // use smaller object for session data 
      $jobseekerinfo = new stdClass;
      $jobseekerinfo->jobseeker_id = $basicInfo->jobseeker_id; 
      $jobseekerinfo->jobseeker_name = $basicInfo->jobseeker_name;
      $jobseekerinfo->jobseeker_email = $basicInfo->jobseeker_email;
      $app->setUserState("jobseeker_registers_basicinfo",$jobseekerinfo);
      
      // force session to write 
      $session = PFactory::getSession();
      $session->close(); 

      $tmpl = new OCP\Template('interview', 'result','base');
      $tmpl->assign('no_reg', true);
      $tmpl->assign('token', $token);
      $tmpl->assign('has_verified_token', $has_verified_token);
      $tmpl->assign('isPaperSet', $isPaperSet);
      $tmpl->assign('isInviteToken', $isInviteToken);
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('todo_list_text', $todo_list_text);
      $tmpl->assign('isRegistered', $isRegistered);
      $tmpl->assign('page_title', $page_title);
      $tmpl->printPage();
   }

   // if anything goes wrong, show this page
   public static function error() {
      disableIECache();
      $tmpl = new OCP\Template('interview', 'error','base');
      $tmpl->assign('no_reg', true);
      $tmpl->assign('page_title', 'error');
      $tmpl->printPage();
   }

}
